let store = {
  storage: window.localStorage,
  session: {
    storage: window.sessionStorage
  }
}

const api = {
  set (key, val) {
    if (val === undefined) {
      return this.remove(key)
    }
    this.storage.setItem(key, serialize(val))
    return val
  },

  get (key, def) {
    let val = deserialize(this.storage.getItem(key))
    return (val === undefined ? def : val)
  },

  has (key) {
    return this.get(key) !== undefined
  },

  remove (key) {
    this.storage.removeItem(key)
  },

  clear () {
    this.storage.clear()
  }
}

Object.assign(store, api)

Object.assign(store.session, api)

function serialize (val) {
  return JSON.stringify(val)
}

function deserialize (val) {
  if (typeof val !== 'string') {
    return undefined
  }
  try {
    return JSON.parse(val)
  } catch (e) {
    return val || undefined
  }
}

export default store
